package com.demo.juc.locks;

import java.util.concurrent.TimeUnit;

/**
 * @Author: yaoshubin
 * @Date: 2023-07-16  16:41
 * @Description: 1）写一个死锁的案例代码
 * 2) 如何排查死锁？
 * jps -l 查看进程号
 * jstack + 进程号
 * <p>
 * jconsole
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        Object objA = new Object();
        Object objB = new Object();

        new Thread(() -> {
            synchronized (objA) {
                System.out.println(Thread.currentThread().getName() + "持有锁A，等待获取锁B");
                //保证B能够切换过去
                try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e);}
                //如果能获取成功，这行应该能打印出来
                synchronized (objB) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁B");
                }
            }
        }, "A").start();

        new Thread(() -> {
            synchronized (objB) {
                System.out.println(Thread.currentThread().getName() + "持有锁B，等待获取锁A");
                //保证A能够切换过去
                try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e);}
                //如果能获取成功，这行应该能打印出来
                synchronized (objA) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁A");
                }
            }
        }, "B").start();

    }
}
